package com.lanou.musicbox.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.lanou.musicbox.R;
import com.lanou.musicbox.adapter.LyricAdapter;
import com.lanou.musicbox.adapter.localmusic.PopupWindowAdapter;
import com.lanou.musicbox.base.BaseActivity;
import com.lanou.musicbox.bean.LyricSentence;
import com.lanou.musicbox.custom.Events;
import com.lanou.musicbox.entity.Entity;
import com.lanou.musicbox.fragment.IMusicBackService;
import com.lanou.musicbox.lrc.LyricDownloadManager;
import com.lanou.musicbox.lrc.LyricLoadHelper;
import com.lanou.musicbox.service.MusicService;
import com.lanou.musicbox.utils.MyConfig;
import com.lanou.musicbox.utils.VolleySingleton;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.io.File;
import java.util.List;

/**
 * Created by dllo on 15/11/3.
 */
public class PlayActivity extends BaseActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    public static final int MSG_UPDATE_UI = 0;
    public static final int MSG_UPDATE_SEEKBAR = 1;
    public static final int MSG_UPPALY_BTN = 2;
    public static final int PLAY_CATEGORY = 3;

    private ImageButton btn_playPre, bt_play, btn_playNext;
    private IMusicBackService bService;
    private SeekBar mseekbar;
    private TextView currentTime_tv, totalTime_tv, enter_play_name, enter_author, current_mode;
    private ImageView move_iv, music_info_back;
    private ImageButton btn_mode;
    private String duration;
    private String current_time;

    private static List<Entity> mp3Infos;

    private static String music_singer, music_name, music_pic;

    private ImageLoader imageLoader;
    private ImageButton btn_more;
    private View view;
    private ListView list;
    private ImageView share_music_btn;
    //歌词

    private LyricLoadHelper mLyricLoadHelper;
    private LyricAdapter mLyricAdapter;
    private TextView mLrcEmptyView;
    private ListView mLrcListView;
    private PopupWindow popupWindow;
    private static String whatMusic;
    private UMSocialService mController;
    private UpdateUiBroadcastReceiver mUpdateUiBroadcastReceiver; //定义全局监听器

    private int indexMusic = 0;
    private String lyricFilePath;
    private String songs_link;


    private String mode_choose[] = {"循环模式", "随机播放", "单曲循环"};
    /**
     * 默认为：循环模式 0: 代表循环播放 1： 代表随机播放 2： 代表单曲播放
     */
    public static int mode_isloop = 0;
    public static void startPlayActivity(Context context, List<Entity> mp3Infos, String whatMusic,
                                         String music_singer, String music_name, String music_pic) {
        PlayActivity.mp3Infos = mp3Infos;
        PlayActivity.whatMusic = whatMusic;
        PlayActivity.music_name = music_name;
        PlayActivity.music_singer = music_singer;
        PlayActivity.music_pic = music_pic;
        Intent intent = new Intent(context, PlayActivity.class);
        Log.i("Sysout", "PlayActivity->mpsInfos.size" + mp3Infos.size() + whatMusic);
        context.startActivity(intent);
    }
    public void onEvent(Events.NewSongsEvent musicInfoEvent) {
        mp3Infos = musicInfoEvent.getSongsInfos();
        whatMusic = musicInfoEvent.getWhatMusic();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.enter_play);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MainActivity.UPDATE_UI); // 添加动作
        // registerReceiver注册方法 (动态注册)
        mUpdateUiBroadcastReceiver = new UpdateUiBroadcastReceiver();
        this.registerReceiver(mUpdateUiBroadcastReceiver, intentFilter);

        // 歌词秀设置---------------------------------------------------------------
        mLyricAdapter = new LyricAdapter(this);

        mLyricLoadHelper = new LyricLoadHelper();
        mLyricLoadHelper.setLyricListener(mLyricListener);
        // 首先在您的Activity中添加如下成员变量
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");

        // 添加QQ平台
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qqSsoHandler.addToSocialSDK();


        // 添加qq空间平台
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
        initData();

    }

    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {
        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            if (lyricSentences != null) {
                Log.i("asdasd", "onLyricLoaded--->歌词句子数目=" + lyricSentences.size()
                        + ",当前句子索引=" + index);
                mLyricAdapter.setLyric(lyricSentences);
                mLyricAdapter.setCurrentSentenceIndex(index);
                mLyricAdapter.notifyDataSetChanged();
                // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
                // mHandler.sendMessageDelayed(
                // Message.obtain(null, MSG_SET_LYRIC_INDEX, index, 0),
                // 100);
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            mLyricAdapter.notifyDataSetChanged();
            mLrcListView.smoothScrollToPositionFromTop(indexOfCurSentence,
                    mLrcListView.getHeight() / 2, 500);
        }
    };

    private void initData() {

        currentTime_tv = (TextView) findViewById(R.id.currentTime_tv);
        totalTime_tv = (TextView) findViewById(R.id.totalTime_tv);
        bt_play = (ImageButton) findViewById(R.id.btn_play);
        btn_playPre = (ImageButton) findViewById(R.id.btn_playPre);
        btn_playNext = (ImageButton) findViewById(R.id.btn_playNext);
        btn_mode = (ImageButton) findViewById(R.id.btn_mode);
        enter_play_name = (TextView) findViewById(R.id.enter_play_name);
        enter_author = (TextView) findViewById(R.id.enter_author);
        mseekbar = (SeekBar) findViewById(R.id.playback_seekbar);
        move_iv = (ImageView) findViewById(R.id.move_iv);
        btn_more = (ImageButton) findViewById(R.id.btn_more);
        music_info_back = (ImageView) findViewById(R.id.music_info_back);
        current_mode = (TextView) findViewById(R.id.current_mode);
        mLrcListView = (ListView) findViewById(R.id.lyricshow);
        mLrcEmptyView = (TextView) findViewById(R.id.lyric_empty);
        share_music_btn = (ImageView) findViewById(R.id.share_music_btn);
        View view1 = getLayoutInflater().inflate(R.layout.noview, null);

        mLrcListView.addFooterView(view1);
        mLrcListView.setAdapter(mLyricAdapter);
        mLrcListView.setEmptyView(mLrcEmptyView);

        mLrcListView.startAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        btn_more.setOnClickListener(this);
        btn_mode.setOnClickListener(this);
        bt_play.setOnClickListener(this);
        btn_playPre.setOnClickListener(this);
        btn_playNext.setOnClickListener(this);
        enter_play_name.setOnClickListener(this);
        enter_author.setOnClickListener(this);
        mseekbar.setOnSeekBarChangeListener(this);
        music_info_back.setOnClickListener(this);
        share_music_btn.setOnClickListener(this);
        imageLoader = VolleySingleton.getInstance(this).getImageLoader();

        enter_play_name.setText(music_name);
        enter_author.setText(music_singer);

        Log.i("lanou78787788", "initData " + music_pic);
        if (music_pic != null && music_pic.startsWith("http")) {
            ImageLoader.ImageListener imageListener = ImageLoader.getImageListener
                    (move_iv, R.mipmap.main_bg03, R.mipmap.main_bg03);
            imageLoader.get(music_pic, imageListener);
        } else {
            move_iv.setImageResource(R.mipmap.main_bg03);
            Log.i("lanou48484", "initData " + music_pic);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mode_isloop = MyConfig.getSharePreInt(this, "which_mode", "chooseMode");
        Log.i("lanou12122", "onResume_mode_isloop " + mode_isloop);
        current_mode.setText(mode_choose[mode_isloop]);
    }

    //接收到发过来的广播,更新 ui
    public class UpdateUiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            mHandler.sendEmptyMessage(MSG_UPDATE_UI);
        }
    }

    /**
     * 和服务绑定
     **/
    public ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bService = IMusicBackService.Stub.asInterface(service);
            // 启动线程
            new Thread(new MyThread()).start();
            new Thread(new UpPlayBtnThread()).start();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bService = null;

        }
    };

    //开始，绑定服务
    @Override
    protected void onStart() {
        super.onStart();

        bindService(new Intent(this, MusicService.class), connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUpdateUiBroadcastReceiver);
        unbindService(connection);
    }

    @Override
    public void onClick(View v) {

        PopupWindow();
        Log.i("是否获得歌曲信息", "————————" + mp3Infos.size() + " kk" + mp3Infos.get(1).getTitle());
        switch (v.getId()) {
            case R.id.btn_play: //播放,暂停
                try {

                    if (bService.getMusicIsPlaying()) {
                        bt_play.setBackgroundResource(R.drawable.bt_pause_music);
                        bService.pauseMusic();
                    } else {
                        bt_play.setBackgroundResource(R.drawable.bt_play_music);
                        bService.playMusic();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_playNext: //下一曲
                try {
                    Log.i("lanou89979", "onClick_下 ");
                    bService.PlayNextMusic();

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_playPre: //上一曲
                try {
                    bService.playUpMusic();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_mode: //模式选择
                ChooseMode();
                break;
            case R.id.btn_more: //列表,更多歌曲
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    Log.i("lanou89595", "onClick_1 ");
                } else {
                    Log.i("lanou89595", "onClick_2 ");
                    popupWindow.showAtLocation(view, Gravity.RIGHT | Gravity.BOTTOM, 0, 140);
                }
                break;
            case R.id.music_info_back:
                finish();
                break;
            case R.id.share_music_btn:
                try {
                    indexMusic = bService.getNowPlay();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                if (whatMusic!=null&&!whatMusic.equals("本地")){
                    songs_link = mp3Infos.get(indexMusic).getUrl();
                }
                //设置分享的内容
                mController.setShareContent(music_name+" "+music_singer);
                if (whatMusic!=null&&!whatMusic.equals("本地")&&songs_link!=null){
                    mController.setShareMedia(new UMImage(PlayActivity.this,
                            songs_link));
                    Log.i("lanou5484", "onClick_2 " + songs_link);
                }
                else {
                    Log.i("lanou5484", "onClick "+songs_link);
                    mController.setShareMedia(new UMImage(PlayActivity.this,
                            "这首歌很好听,自己搜索下载吧!"));
                }

                // 是否只有已登录用户才能打开分享选择页
                mController.openShare(PlayActivity.this, false);

                break;
        }

    }

    /**
     * 模式选择
     */

    private void ChooseMode() {
        mode_isloop = (mode_isloop + 1) % PLAY_CATEGORY;
        MyConfig.putSharePre(this, "which_mode", "chooseMode", mode_isloop);
        current_mode.setText(mode_choose[mode_isloop]);
        switch (mode_isloop) {
            case 0: //循环模式
                Log.i("lou3q", "————————————————" + mode_isloop);
                btn_mode.setImageResource(R.mipmap.ic_player_mode_all_pressed);

                try {
                    bService.setRandomPlay(mode_isloop);

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Toast.makeText(this, "循环模式", Toast.LENGTH_SHORT).show();

                break;

            case 1: //随机播放
                btn_mode.setImageResource(R.mipmap.ic_player_mode_random_pressed);

                try {
                    bService.setRandomPlay(mode_isloop);

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Toast.makeText(this, "随机播放", Toast.LENGTH_SHORT).show();
                break;
            case 2: //单曲循环
                btn_mode.setImageResource(R.mipmap.ic_player_mode_single_pressed);
                try {
                    bService.setRandomPlay(mode_isloop);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Toast.makeText(this, "单曲循环", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 弹出歌曲列表
     */
    private void PopupWindow() {
        view = this.getLayoutInflater().inflate(R.layout.popup_window, null);
        TextView songs_num = (TextView) view.findViewById(R.id.songs_count);
        list = (ListView) view.findViewById(R.id.popup_listView);
        if (mp3Infos != null && mp3Infos.size() > 0) {
            PopupWindowAdapter adapter = new PopupWindowAdapter(this, mp3Infos);
            list.setAdapter(adapter);
            songs_num.setText(mp3Infos.size() + "");
        }

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置外部监听
        popupWindow.setOutsideTouchable(false);//设置非 popupWindow 不可触摸
        popupWindow.setFocusable(true); //可获得焦点
        popupWindow.setTouchable(true); //设置可触摸
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭
                popupWindow.dismiss();

            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    if (bService.getMusicIsPlaying()) {
                        bService.stopMusic();
                    }
                    if (whatMusic != null && whatMusic.equals("网络")) {
                        bService.setNowPlay(position);
                    } else {
                        bService.setNowPlay(position);
                        bService.setDataSourceAndPlay();
                    }
                    updateUi();
                    bt_play.setBackgroundResource(R.drawable.bt_play_music);

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * seekbar的监听
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mseekbar.setProgress(progress);
            try {
                bService.setProgress(progress);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    /**
     * 读取本地歌词文件
     */
    public void loadLyric(List<Entity> playingSong) {

        if (playingSong == null) {
            return;
        }
        // 取得歌曲同目录下的歌词文件绝对路径
        if (indexMusic < playingSong.size() + 1) {
            lyricFilePath = LyricDownloadManager.lrcPath + "/" + playingSong.get(indexMusic).getTitle() + ".lrc";
        }


        File lyricfile = new File(lyricFilePath);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            // Log.i("dasdasd", "loadLyric()--->本地有歌词，直接读取");
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else {

            mLyricLoadHelper.loadLyric(null);
            //Toast.makeText(this, "没有歌词赶紧去下载吧", Toast.LENGTH_SHORT).show();

        }
    }

    /**
     * 当前播放歌曲改变时。activity界面更新
     *
     * @throws RemoteException
     */
    private void updateUi() throws RemoteException {
        if (mp3Infos != null && bService.getNowPlay() < mp3Infos.size()) {

            indexMusic = bService.getNowPlay();
            if (whatMusic!=null&&!whatMusic.equals("本地")&&songs_link!=null){
                songs_link = mp3Infos.get(indexMusic).getUrl();
            }
            music_name = mp3Infos.get(indexMusic).getTitle();
            music_singer = mp3Infos.get(indexMusic).getArtist();
            enter_play_name.setText(music_name);
            enter_author.setText(music_singer);
            music_pic = mp3Infos.get(indexMusic).getBig_pic();
            if (music_pic != null && music_pic.startsWith("http")) {
                ImageLoader.ImageListener imageListener = ImageLoader.getImageListener
                        (move_iv, R.mipmap.main_bg03, R.mipmap.main_bg03);
                imageLoader.get(music_pic, imageListener);
            } else {
                move_iv.setImageResource(R.mipmap.main_bg03);
            }
        }

        Log.i("是否获得歌曲信息", "————————" + music_name + "歌手" + music_singer);

    }

    //根据接收的消息,处理UI更新
    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case MSG_UPDATE_UI:
                    try {

                        updateUi();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case MSG_UPDATE_SEEKBAR:
                    try {
                        current_time = bService.getNowPlayingMusicCurTime();
                        currentTime_tv.setText(current_time + "");//当前的时间
                        duration = bService.getNowPlayingMusicMaxTime();
                        totalTime_tv.setText(duration);  //总长度
                        mseekbar.setMax(bService.getNowPlayingMaxTime());
                        mseekbar.setProgress(bService.getNowPlayingCurTime());
                        indexMusic = bService.getNowPlay();
                        loadLyric(mp3Infos);
                        mLyricLoadHelper.notifyTime(bService.getNowPlayingCurTime());


                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case MSG_UPPALY_BTN:
                    try {
                        if (bService.getMusicIsPlaying()) {
                            bt_play.setBackgroundResource(R.drawable.bt_play_music);
                            updateUi();

                        } else {
                            bt_play.setBackgroundResource(R.drawable.bt_pause_music);

                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    break;

            }

            super.handleMessage(msg);
        }

    };

    private boolean mBlRun = true;

    /**
     * 用于更新时间和seekbar的线程
     *
     * @author Administrator
     */
    public class MyThread implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (mBlRun) {
                try {
                    if (bService.getMusicIsPlaying()) {
                        mHandler.sendEmptyMessage(MSG_UPDATE_SEEKBAR);
                    }

                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 开启一个刷新按键和歌手信息的线程
     */

    public class UpPlayBtnThread implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (mBlRun) {

                mHandler.sendEmptyMessage(MSG_UPPALY_BTN);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}